package chat;

import java.util.Set;
import java.util.concurrent.*;

public class ChatRoom {
    private final Set<User> onlineUsers = ConcurrentHashMap.newKeySet();
    private final BlockingQueue<Message> messageQueue = new LinkedBlockingQueue<>();
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    public void registerUser(User user) {
        onlineUsers.add(user);
    }

    public void unregisterUser(User user) {
        onlineUsers.remove(user);
    }

    public boolean isUserOnline(User user) {
        return onlineUsers.contains(user);
    }

    public void sendMessage(User sender, String content) {
        Message message = new Message(sender, content);
        messageQueue.offer(message);
    }

    public ChatRoom() {
        executorService.submit(() -> {
            try {
                while (true) {
                    Message message = messageQueue.take();
                    broadcastMessage(message);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    private void broadcastMessage(Message message) {
        for (User user : onlineUsers) {
            // In a real implementation, you would send the message to each user's client.
            // Here, we just print it to the console for demonstration purposes.
            System.out.println(message);
        }
    }

    public void shutdown() {
        executorService.shutdown();
        try {
            executorService.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}